package com.ms.qw.infraestructura.persistence.jpa.sigar;

import org.hibernate.HibernateException;
import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.List;

/**
 * User: jmacavilca
 * Date: 28/12/11
 */
public class JpaHbmBeanResultTransformer implements ResultTransformer {
    private final Class resultClass;
    boolean ignoreNonWritableProperty = false;

    public JpaHbmBeanResultTransformer(Class resultClass) {
        this.resultClass = resultClass;
    }

    public JpaHbmBeanResultTransformer setIgnoreNonWritableProperty(boolean ignoreNonWritableProperty) {
        this.ignoreNonWritableProperty = ignoreNonWritableProperty;
        return this;
    }

    public Object transformTuple(Object[] tuple, String[] aliases) {
        Object result;

        try {
            result = resultClass.newInstance();
            BeanWrapper wrap = new BeanWrapperImpl(result);
            for (int i = 0; i < aliases.length; i++) {
                String alias = aliases[i];
                if (ignoreNonWritableProperty && !wrap.isWritableProperty(alias))
                    continue;
                wrap.setPropertyValue(alias, tuple[i]);
            }
        } catch (InstantiationException e) {
            throw new HibernateException("Could not instantiate resultclass: " + resultClass.getName());
        } catch (IllegalAccessException e) {
            throw new HibernateException("Could not instantiate resultclass: " + resultClass.getName());
        }

        return result;
    }

    public List transformList(List collection) {
        return collection;
    }
}
